package com.example.springboottest.integration.file;

import java.io.File;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.dsl.MessageChannels;
import org.springframework.integration.file.FileWritingMessageHandler;
import org.springframework.integration.file.dsl.Files;
import org.springframework.integration.file.support.FileExistsMode;
import org.springframework.integration.transformer.GenericTransformer;
import org.springframework.messaging.MessageChannel;

@Configuration
public class FileWriterIntegrationConfig {
    /**
     * IntegrationFlow 直接定义了流程，可以省掉下面单独定义的@ServiceActivator和@Transformer等
     * @return
     */
//    @Bean
//    public IntegrationFlow fileWriterFlow() {
//        return IntegrationFlows
//                .from(MessageChannels.direct("textInChannel"))// ⼊站通道
//                .<String, String>transform(t -> t.toUpperCase()) // 声明转换器
//                .handle(Files // 处理⽂件写⼊
//                        .outboundAdapter(new File("/tmp/sia5/files"))
//                        .fileExistsMode(FileExistsMode.APPEND)
//                        .appendNewLine(true))
//                .get();
//    }

    @Bean
    @Transformer(inputChannel = "textInChannel", //声明转换器
            outputChannel = "fileWriterChannel")
    public GenericTransformer<String, String> upperCaseTransformer() {
        return text -> text.toUpperCase();
    }

    @Bean
    @ServiceActivator(inputChannel = "fileWriterChannel")
    public FileWritingMessageHandler fileWriter() { //声明⽂件写⼊器
        FileWritingMessageHandler handler =
                new FileWritingMessageHandler(new File("/Users/fangdaye/work/workspace/spring-boot-test/src/main/java/com/example/springboottest/integration/file/data"));
        handler.setExpectReply(false);
        handler.setFileExistsMode(FileExistsMode.APPEND);
        handler.setAppendNewLine(true);
        return handler;
    }

    /**
     * DirectChannel最简单的channel，表示点对点
     *
     * @return
     */
    @Bean
    public MessageChannel textInChannel() {
        return new DirectChannel();
    }

    @Bean
    public MessageChannel fileWriterChannel() {
        return new DirectChannel();
    }
}